<template>
  <div class="container">
    <div class="logo">
      <img src="http://static.catone-vip.com/20190228/5c778d3534feb">
    </div>
    <van-cell-group :border="false">
      <van-field
        :value="form.phone"
        data-name="phone"
        placeholder="请输入手机号"
        clearable
        @change="onChangeField"
      />
      <van-field
        :value="form.code"
        data-name="code"
        clearable
        center
        placeholder="请输入短信验证码"
        @change="onChangeField"
        use-button-slot
      >
        <van-button
          class="mk-button"
          slot="button"
          size="small"
          type="default"
          :disabled="send_code_btn_disabled"
          @click="sendCode"
        >{{send_code_btn_text}}</van-button>
      </van-field>
      <van-field :value="form.password" data-name="password" type="password" clearable placeholder="请输入密码" @change="onChangeField"/>
    </van-cell-group>
    <div class="btn">
      <van-button class="mk-button" type="primary" size="normal" block :loading="bindLoading" @click="onSubmit">立刻绑定</van-button>
    </div>
    <div class="tips">
      <p>如果您已在美控家其他渠道使用手机号注册过，请直接用手机号登陆 <span @click="targetLogin">去登录<van-icon style="display:flex;" name="arrow" color="#E6648C" /></span></p>
    </div>
    <a class="switch-btn" @click="onSwitchIgnore">暂不绑定</a>
    <van-toast id="van-toast"/>
    <van-dialog id="van-dialog"/>
  </div>
</template>

<script>
import * as CommonAction from '@/api/common'
import Toast from 'vant-weapp/dist/toast/toast'
import Dialog from 'vant-weapp/dist/dialog/dialog'
import Utils from '@/utils'
import * as AuthAction from '@/api/auth'
import {mapState} from 'vuex'

export default {
  data () {
    return {
      form: {},
      send_code_btn_text: '发送验证码',
      send_code_btn_disabled: false,
      bindLoading: false,
      disIgnore: false,
      timer: 0
    }
  },
  computed: {
    ...mapState(['me'])
  },
  methods: {
    onChangeField (event) {
      this.form[event.currentTarget.dataset.name] = event.mp.detail
    },
    onSwitchIgnore () {
      Dialog.confirm({
        title: '确认跳过绑定?',
        message: '跳过绑定将为您创建新的美控家账号，如果您已经使用手机号在美控家其它渠道注册过，请直接登录。'
      }).then(() => {
        this.onIgnore()
      }).catch(() => {})
    },
    targetLogin () {
      wx.navigateTo({ url: './login-phone' })
    },
    onIgnore () {
      if (this.disIgnore) return
      delete this.form.phone
      delete this.form.code
      this.form.mp_openid = wx.getStorageSync('openid')
      if (wx.getStorageSync('__inviteCode')) {
        this.form.invite_code = wx.getStorageSync('__inviteCode')
      }
      this.disIgnore = true
      AuthAction.wxFastLogin(this.form).then(data => {
        this.disIgnore = false
        wx.setStorageSync('token', data.token)
        this.$store.commit('set_me', data.me)
        this.handleTarget()
      }).catch(err => {
        this.disIgnore = false
        Toast(err.msg)
      })
    },
    onSubmit () {
      if (!this.form.phone) {
        Toast('手机号不能为空')
        return
      }
      if (!this.form.password) {
        Toast('密码不能为空')
        return
      }
      if (!this.form.code) {
        Toast('请输入验证码')
        return
      }
      if (!Utils.validator.isMobile(this.form.phone)) {
        Toast('请输入有效的手机号')
      }
      if (wx.getStorageSync('__inviteCode')) {
        this.form.invite_code = wx.getStorageSync('__inviteCode')
      }
      this.form.mp_openid = wx.getStorageSync('openid')
      if (this.bindLoading) return
      this.bindLoading = true
      AuthAction.register(this.form).then(data => {
        wx.setStorageSync('token', data.token)
        this.$store.commit('set_me', data.me)
        this.handleTarget()
        this.bindLoading = false
      }).catch(err => {
        Toast(err.msg)
        this.bindLoading = false
      })
    },
    sendCode () {
      if (this.timer > 0) return
      if (!this.form.phone) {
        Toast('手机号不能为空')
        return
      }
      if (!Utils.validator.isMobile(this.form.phone)) {
        Toast('请输入有效的手机号')
        return
      }
      this.timer = 60
      this.send_code_btn_text = this.timer + 's'
      this.send_code_btn_disabled = true
      var that = this
      var t = setInterval(function () {
        that.timer = that.timer - 1
        if (that.timer === 0) {
          clearInterval(t)
          that.send_code_btn_disabled = false
          that.send_code_btn_text = '发送验证码'
        } else {
          that.send_code_btn_text = that.timer + 's'
        }
      }, 1000)
      CommonAction.sendVerifyCode({ phone: this.form.phone })
        .then(() => {
          Toast('验证码已发送，请注意查看~')
        })
        .catch(err => Toast(err.msg))
    },
    handleTarget () {
      if (this.$root.$mp.query.target) {
        switch (this.$root.$mp.query.target) {
          case 'cart':
            wx.switchTab({ url: '../cart/index' })
            break
          case 'goods':
            wx.redirectTo({ url: '../product/detail?id=' + this.$root.$mp.query.id })
            break
          case 'posts':
            wx.redirectTo({ url: '../shop/index?name=' + this.$root.$mp.query.name })
            break
          case 'zy':
            wx.switchTab({ url: '../home/zy' })
            break
          case 'post-detail':
            wx.redirectTo({
              url: '../post/detail?name=' + this.$root.$mp.query.name + '&id=' + this.$root.$mp.query.id
            })
            break
        }
      } else {
        wx.switchTab({
          url: '../user/index'
        })
      }
    },
    fetchUserInfo () {
      let that = this
      wx.getUserInfo({
        lang: 'zh_CN',
        success: function (res) {
          that.form.sex = res.userInfo.gender
          that.form.nickname = res.userInfo.nickName
          that.form.avatar = res.userInfo.avatarUrl
          that.form.country = res.userInfo.country
          that.form.province = res.userInfo.province
          that.form.city = res.userInfo.city
        },
        fail (res) {
          Toast(res)
        }
      })
    }
  },
  beforeMount () {
    this.fetchUserInfo()
  }
}
</script>

<style lang="less" scoped>
.container {
  height: 667px;
  position: relative;
  .btn {
    margin: 0rpx 30rpx 30rpx;
  }
  .logo {
    display: flex;
    margin: 70rpx 0 150rpx;
    img {
      width: 140rpx;
      height: 140rpx;
      margin: 0 auto;
    }
  }
  .switch-btn {
    width: 96%;
    text-align: right;
    background: #ffffff;
    font-size: 28rpx;
    color: #525354;
  }
  .tips{
    height:85rpx;
    padding:10rpx 30rpx;
    p {
      width:100%;
      font-size:23rpx;
      text-align:left;
      color:#88898a;
      padding:0 10rpx;
      span {
        display: flex;
        align-items: center;
        color: #E6648C;
      }
    }
  }
}
</style>
